package com.xingxuecn.limit.service.impl;

import com.xingxuecn.limit.common.Constant;
import com.xingxuecn.limit.common.model.dto.User;
import com.xingxuecn.limit.common.model.vo.Page;
import com.xingxuecn.limit.common.model.vo.ResultModel;
import com.xingxuecn.limit.dao.UserDao;
import com.xingxuecn.limit.dao.impl.UserDaoImpl;
import com.xingxuecn.limit.service.UserService;

import org.apache.struts2.ServletActionContext;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpSession;

/**
 * @author Kris at 2018/9/13 10:39
 */
public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();

    @Override
    public Page<User> searchPage(User user, Integer page, Integer rows) throws SQLException {
        return userDao.searchPage(user, page, rows);
    }

    @Override
    public int add(User user) throws SQLException {
        return userDao.add(user);
    }

    @Override
    public int update(User user) throws SQLException {
        return userDao.update(user);
    }

    @Override
    public int delete(Integer id) throws SQLException {
        return userDao.delete(id);
    }

    @Override
    public ResultModel doLogin(String account, String pwd) {
        User params = new User();
        params.setAccount(account);
        try {
            List<User> userList = userDao.search(params);
            if (userList == null || userList.isEmpty()) {
                return new ResultModel(500, "登陆失败：用户名或密码错误");
            }
            User user = userList.get(0);
            if(!user.getPwd().equals(pwd)){
                return new ResultModel(500, "登陆失败：用户名或密码错误");
            }
            //存入session以前把用户的密码删掉，以免不小心暴露到jsp
            user.setPwd(null);
            HttpSession session = ServletActionContext.getRequest().getSession();
            session.setMaxInactiveInterval(60*10);
            session.setAttribute(Constant.USER_SESSION_KEY,user);
            return new ResultModel<User>(200, "登陆成功",user);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultModel(500, "登陆失败：" + e.getMessage());
        }
    }
}
